#include "drawingviewcontainer.h"
#include "drawingview.h"
#include <QMenu>
#include <QTabBar>
#include <application.h>

DrawingViewContainer::DrawingViewContainer(QWidget *parent) :
    QTabWidget(parent)
{
    setTabPosition(QTabWidget::South);
    setTabShape(QTabWidget::Triangular);
    setTabsClosable(true);
    setDocumentMode(true);

    tabBar()->setContextMenuPolicy(Qt::CustomContextMenu);

    connect(this, SIGNAL(tabCloseRequested(int)), this, SLOT(onRemoveTab(int)));
    connect(tabBar(), SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(onContextMenu(const QPoint&)));

    connect(this, SIGNAL(currentChanged(int)), this, SLOT(onTabChanged(int)));
    connect(&Application::app(), SIGNAL(activeDocumentChanged(QPointer<Document>)),
            this, SLOT(onActiveDocumentChanged(QPointer<Document>)));
    connect(&Application::app(), SIGNAL(documentRemoved(QPointer<Document>)),
            this, SLOT(onDocumentRemoved(QPointer<Document>)));
}

void DrawingViewContainer::addDocument(QPointer<Document> doc)
{
    QPointer<DrawingView> view = new DrawingView(doc, this);
    int newIndex = addTab(view, doc->title());
    // switch manualy to new tab
    setCurrentIndex(newIndex);
}

void DrawingViewContainer::onRemoveTab(int index)
{
    QPointer<DrawingView> view = qobject_cast<DrawingView*>(widget(index));
    if(view)
    {
        emit closeDocument(view->document());
    }
}

void DrawingViewContainer::onContextMenu(const QPoint &point)
{
    if(point.isNull())
    {
        return;
    }

    int tab = -1;
    if((tab = tabBar()->tabAt(point)) != -1)
    {
        QMenu* pMenu = new QMenu(this);
        QAction* pCloseAction = pMenu->addAction("Close");

        pMenu->exec(tabBar()->mapToGlobal(point));
    }
}

void DrawingViewContainer::onTabChanged(int index)
{
    QPointer<DrawingView> view = qobject_cast<DrawingView*>(widget(index));
    if(view)
    {
        QPointer<Document> doc = view->document();
        if(doc)
        {
            Application::app().setActiveDocument(doc);
        }
    }
}

void DrawingViewContainer::onActiveDocumentChanged(QPointer<Document> doc)
{
    for(int i=0;i<count();i++)
    {
        QPointer<DrawingView> view = qobject_cast<DrawingView*>(widget(i));
        if(view && (view->document() == doc))
        {
            setCurrentIndex(i);
            break;
        }
    }
}

void DrawingViewContainer::onDocumentRemoved(QPointer<Document> doc)
{
    for(int i=0;i<count();i++)
    {
        QPointer<DrawingView> view = qobject_cast<DrawingView*>(widget(i));
        if(view && (view->document() == doc))
        {
            view->deleteLater();
            removeTab(i);
            break;
        }
    }
}
